package com.system.orderserver.controller;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.system.commonutils.bean.ApiResult;
import com.system.commonutils.bean.PagesBean;
import com.system.commonutils.pojo.UserInfo;
import com.system.commonutils.utils.RedisUtil;
import com.system.orderserver.bus.OrderSender;
import com.system.orderserver.pojo.UserInfoOrder;
import com.system.orderserver.result.*;
import com.system.orderserver.service.OrderService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

@RestController
@Api(value = "订单数据",tags = "订单数据接口API")
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    private OrderService orderService;

    @Autowired
    OrderSender orderSender;


    @Autowired
    RedisUtil redisUtil;


    @RequestMapping(value = "/selectOrderInfo",method = RequestMethod.POST)
    @ApiOperation(value = "根据订单ID查询订单详情",notes = "查看订单详细信息")
    @ApiImplicitParam(name = "orderId",value = "订单ID",required = true,dataType = "int",paramType = "query")
    public ApiResult<OrdersInfo_Result> selectOrderInfo(Integer orderId){
        OrdersInfo_Result info = orderService.selectOrderInfo(orderId);
        if(info!=null){
            ApiResult<OrdersInfo_Result> apiResult = new ApiResult(200,"成功",info);
            return apiResult;
        }else{
            return new ApiResult<>(200,"没有该订单信息");
        }
    }

    @RequestMapping(value = "/selectOrders",method = RequestMethod.POST)
    @ApiOperation(value = "查询订单",notes = "查询订单（包括条件查询）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "limit",value = "每页显示条数",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "orderNo",value = "订单号",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "ordersState",value = "订单状态",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "startTiem",value = "日期时间范围(初始时间)",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTiem",value = "日期时间范围（结束时间）",required = false,dataType = "String",paramType = "query"),
    })
    public PagesBean<OrdersList_Result> selectOrders(Integer page,Integer limit,String orderNo,Integer ordersState,String startTiem,String endTiem){
        List<OrdersList_Result> list = orderService.selectOrders(page,limit,orderNo,ordersState,startTiem,endTiem);
        Integer count = orderService.countOrder(orderNo,ordersState,startTiem,endTiem);
        PagesBean<OrdersList_Result> pagesBean = new PagesBean<>();
        pagesBean.setData(list);
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(limit);
        pagesBean.setDataCount(count);
        return  pagesBean;
    }


    @RequestMapping(value = "/deleteOrder",method = RequestMethod.POST)
    @ApiOperation(value = "删除订单",notes = "根据订单ID删除订单")
    @ApiImplicitParam(name = "orderId",value = "订单ID",required = true,dataType = "int",paramType = "query")
    public ApiResult deleteOrder(Integer orderId){
        String msg = orderService.deleteOrder(orderId);
        return new ApiResult(200,msg);
    }

    @RequestMapping(value = "/addOrder",method = RequestMethod.POST)
    @ApiOperation(value = "模拟用户添加订单",notes = "用户添加订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "couponId",value = "优惠券id",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "ordersState",value = "订单状态",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "harvestType",value = "收货类型（1.配送上门  2.自提）",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "paymentMethod",value = "支付方式",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "logisticsId",value = "物流id",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "selfAddressId",value = "自提地址id（自提地址和收货地址任选其一）",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "userAddressId",value = "用户收获地址id（自提地址和收货地址任选其一）",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "goodsId",value = "商品id（多个商品用,隔开）",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "goodsNumber",value = "商品数量（,隔开）",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "specificationsId",value = "商品规格（,隔开）",required = true,dataType = "String",paramType = "query"),
    })
    public ApiResult addOrder(Integer userId,Integer couponId ,Integer ordersState,Integer harvestType,
                              Integer paymentMethod,Integer logisticsId,Integer selfAddressId,Integer userAddressId,
                              String goodsId,String goodsNumber,String specificationsId){
        String msg = orderService.addOrder( userId, couponId , ordersState, harvestType,paymentMethod,
                logisticsId, selfAddressId, userAddressId,goodsId, goodsNumber, specificationsId);


        return new ApiResult(200,msg);
    }


    @RequestMapping(value = "/selectNotDeliveredOrders",method = RequestMethod.POST)
    @ApiOperation(value = "查询未发货订单列表",notes = "查询未发货订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "limit",value = "每页显示条数",required = true,dataType = "int",paramType = "query"),
    })
    public PagesBean<NotDeliveredOrdersResult> selectNotDeliveredOrders(Integer page,Integer limit){;
        List<NotDeliveredOrdersResult> list = orderService.selectNotDeliveredOrders(page,limit);
        PagesBean<NotDeliveredOrdersResult> pagesBean = new PagesBean();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(limit);
        pagesBean.setDataCount(orderService.selectNotDeliveredOrdersCount());
        pagesBean.setData(list);
        return  pagesBean;
    }


    @RequestMapping(value = "deliverGoods",method = RequestMethod.POST)
    @ApiOperation(value = "订单发货",notes = "订单发货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单id",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "logisticsNo",value = "物流单号",required = true,dataType = "String",paramType = "query"),
    })
    public ApiResult deliverGoods(Integer orderId ,String logisticsNo ){;
        String msg = orderService.deliverGoods(orderId,logisticsNo);
        orderSender.sendIntegral(orderId);//订单发货，给库存发消息  减少库存
        return  new ApiResult(200,msg);
    }

    @RequestMapping(value = "orderPay",method = RequestMethod.POST)
    @ApiOperation(value = "订单支付",notes = "订单支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单id",required = true,dataType = "int",paramType = "query"),
    })
    public ApiResult orderPay(Integer orderId ){;
        Boolean aBoolean = orderService.orderPay(orderId);

        OrdersInfo_Result ordersInfo_result = orderService.selectOrderInfo(orderId);

        if(aBoolean){
            orderSender.sendOrderMsg(orderId,ordersInfo_result);
           // orderSender.sendIntegral(orderId);
        }
        return  ApiResult.withBoolean(aBoolean);
    }


    @RequestMapping(value = "/selectExceptionOrder",method = RequestMethod.POST)
    @ApiOperation(value = "异常订单查询",notes = "异常订单查询（包括条件查询）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "limit",value = "每页显示条数",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "orderId",value = "订单id",required = false,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "startTime",value = "日期时间范围(初始时间)",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "endTime",value = "日期时间范围（结束时间）",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "userName",value = "处理人",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "exceptionOrdersSpeed",value = "异常订单处理进度",required = false,dataType = "int",paramType = "query"),
    })
    public PagesBean<ExceptionOrder_Result> selectExceptionOrder(Integer page,Integer limit,Integer orderId,
                                                                    String startTime,String endTime,String userName,Integer exceptionOrdersSpeed){;
        List<ExceptionOrder_Result> list = orderService.selectExceptionOrder(page,limit,orderId,startTime,endTime,userName,exceptionOrdersSpeed);
        PagesBean<ExceptionOrder_Result> pagesBean = new PagesBean();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(limit);
        pagesBean.setDataCount(orderService.countExceptionOrder(orderId,startTime,endTime,userName,exceptionOrdersSpeed));
        pagesBean.setData(list);
        return  pagesBean;
    }


    @RequestMapping(value = "/returnGoods",method = RequestMethod.POST)
    @ApiOperation(value = "用户退货、换货、取消订单 接口",notes = "用户退货接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单ID",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "state",value = "状态（1、退货 2、换货 3、取消交易）",required = true,dataType = "int",paramType = "query")
    })
    public ApiResult returnGoods(Integer orderId,Integer state){
       String msg =  orderService.returnGoods(orderId,state);
        return new ApiResult(200,msg);
    }




    @PreAuthorize("isAuthenticated()")
    @RequestMapping(value = "/handleExceptionOrder",method = RequestMethod.POST)
    @ApiOperation(value = "处理异常订单",notes = "处理异常订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId",value = "订单ID",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "yesNo",value = "1.同意  2.不同意",required = true,dataType = "int",paramType = "query"),
    })
    public ApiResult handleExceptionOrder(@ApiParam(hidden = true) OAuth2Authentication authentication, Integer orderId, Integer yesNo){
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        String tokenValue = details.getTokenValue();
        String s = (String) redisUtil.get(tokenValue);
        System.out.println(s);
        UserInfoOrder userBean = redisUtil.get(tokenValue, UserInfoOrder.class);
        String adminName = userBean.getUser_username();
        String msg = orderService.handleExceptionOrder(adminName,orderId,yesNo);
        return new ApiResult(200,msg);

    }

    @RequestMapping(value = "/userSelectOrders",method = RequestMethod.POST)
    @ApiOperation(value = "根据用户id查询用户账单列表",notes = "根据用户id查询用户账单列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "limit",value = "每页显示条数",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name = "userId",value = "用户id",required = true,dataType = "int",paramType = "query")
    })
    public PagesBean<UserOrder_Result> userSelectOrders(Integer userId,Integer page,Integer limit){
        List<UserOrder_Result> list = orderService.userSelectOrders(userId,page,limit);
        PagesBean<UserOrder_Result> pagesBean = new PagesBean();
        pagesBean.setNowsPage(page);
        pagesBean.setPageSize(limit);
        pagesBean.setDataCount(orderService.countUserOrder(userId));
        pagesBean.setData(list);
        return  pagesBean;
    }



}
